package com.ruoyi.commodity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AuthBrand;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.commodity.service.AuthBrandService;
import com.ruoyi.commodity.mapper.AuthBrandMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Admin
* @description 针对表【tb_auth_brand】的数据库操作Service实现
* @createDate 2025-01-17 10:46:13
*/
@Service
public class AuthBrandServiceImpl implements AuthBrandService{


	@Autowired
	private AuthBrandMapper authBrandMapper;

	@Override
	public List<TreeSelect> selectBrandTreeList(AuthBrand brand) {
		List<AuthBrand> brandList = selectList(brand);
		return buildBrandTreeSelect(brandList);
	}

	public List<AuthBrand> selectList(AuthBrand brand) {
		return authBrandMapper.selectList(brand);
	}


	public List<TreeSelect> buildBrandTreeSelect(List<AuthBrand> brandList) {
		List<AuthBrand> brandTree = buildBrandTree(brandList);
		return brandTree.stream().map(TreeSelect::new).collect(Collectors.toList());
	}

	public List<AuthBrand> buildBrandTree(List<AuthBrand> brandList) {
		List<AuthBrand> returnList = new ArrayList<>();
		List<Long> collect = brandList.stream().map(AuthBrand::getAuthBrandId).collect(Collectors.toList());
		// 如果是顶节点，就将所有的子节点通过递归的方式全部查询出来封装到对应父节点中去，如果不是父节点就正常返回
		for (AuthBrand brand : brandList){
			//如果是顶节点，遍历该父节点下的所有子节点
			if(!collect.contains(brand.getParentId())){
				recursionFn(brandList,brand);
				returnList.add(brand);
			}
		}
		if (returnList.isEmpty())
		{
			returnList = brandList;
		}
		return returnList;
	}


	/**
	 * 递归列表
	 * @param brandList 子级
	 * @param brand 父级
	 */
	private void recursionFn(List<AuthBrand> brandList , AuthBrand brand){
		// 得到子节点列表
		List<AuthBrand> childList = getChildList(brandList, brand);
		brand.setChildrenAuthBrandForm(childList);
		for (AuthBrand newBrand : childList)
		{
			if (hasChild(brandList, newBrand))
			{
				recursionFn(brandList, newBrand);
			}
		}
	}

	/**
	 * 获得子节点
	 * @param brandList 所有节点
	 * @param brand 当前遍历节点
	 * @return
	 */
	private List<AuthBrand> getChildList(List<AuthBrand> brandList, AuthBrand brand){
		List<AuthBrand> returnList = new ArrayList<>();
		Iterator<AuthBrand> iterator = brandList.iterator();
		while (iterator.hasNext()){
			AuthBrand n = (AuthBrand) iterator.next();
			if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == brand.getAuthBrandId().longValue())
			{
				returnList.add(n);
			}
		}
		return returnList;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<AuthBrand> brandList, AuthBrand brand)
	{
		return getChildList(brandList, brand).size() > 0;
	}
}




